﻿using AutoMapper;
using Morin.Shared.Common;
using Morin.Shared.Models;
using Morin.Shared.Parameters;
using Morin.Storages;

namespace Morin.Services;

public class ApiService(IMapper mapper, IAppStorage appStorage) : IApiService
{
    public async Task<VideoModel> ReqQryVideoDetailsAsync(ReqQryVideoDetailPara req)
    {
        var uri = ToUri(req);
        var content = await HttpsProvider.GetAsync(uri);
        if (string.IsNullOrEmpty(content)) return new VideoModel();
        var jsonModel = JsonProvider.FromContentToObject<RspVideoDetailJsonDataModel>(content);
        if (jsonModel == null) return new VideoModel();
        var result = mapper.Map<VideoModel>(jsonModel.Videos[0]);
        //  赋来源ID
        result.VodSourceID = req.SourceId;
        return result;

    }

    public async Task<RspQryVideoModel> ReqQryVideosAsync(ReqQryVideoPara req)
    {
        var uri = ToUri(req);
        var content = await HttpsProvider.GetAsync(uri);
        if (string.IsNullOrEmpty(content)) return new RspQryVideoModel();
        var jsonModel = JsonProvider.FromContentToObject<RspVideoListJsonDataModel>(content);
        return jsonModel == null ? new RspQryVideoModel() : mapper.Map<RspQryVideoModel>(jsonModel);
    }

    /// <summary>
    /// 参数转网址
    /// <para>ac=list</para>
    /// <para>t=类别ID</para>
    /// <para>pg=页码</para>
    /// <para>wd=搜索关键字</para>
    /// <para>h=几小时内的数据</para>
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    private string ToUri(Parameter req)
    {
        ArgumentNullException.ThrowIfNull(req);

        if (req.SourceId < 0) return "";

        if (!appStorage.MediaSourceDict.TryGetValue(req.SourceId, out var baseMediaSource)) return "";

        var vodApiQueryString = $"?ac={req.AcName}";

        //  优先Json
        var baseUri = !string.IsNullOrEmpty(baseMediaSource.JsonUri)
            ? baseMediaSource.JsonUri
            : baseMediaSource.XmlUri;

        if (baseUri == null) return "";
        var subUri = new Uri(baseUri);

        var para = "";

        if (!string.IsNullOrEmpty(req.KeyWord)) para += $"&wd={req.KeyWord}";
        if (req.ClassId > 0) para += $"&t={req.ClassId}";
        if (!string.IsNullOrEmpty(req.VodIds)) para += $"&ids={req.VodIds}";
        if (req.Hour > 0) para += $"&h={req.Hour}";
        if (req.PageIndex > 0) para += $"&pg={req.PageIndex}";
        var vodApiPreString = "";
        if (subUri.Segments.Length <= 2) return "";
        foreach (var item in subUri.Segments)
        {
            vodApiPreString += $"{item}";
            if (item.Contains("vod", StringComparison.CurrentCultureIgnoreCase)) break;
        }

        var uriString = $"{subUri.Scheme}://{subUri.Host}{vodApiPreString}{vodApiQueryString}{para}";

        return uriString;

    }
}